package com.myflink.day02;

import com.myflink.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * @author Shelly An
 * @create 2020/9/16 16:04
 * keyBy其实就是groupBy  很常用，因此返回类型很重要
 * 分组是逻辑上的分组，给每个数据打赏标签（属于哪个分组），并不是对并行度进行改变。
 */
public class Transform_KeyBy {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        DataStreamSource<String> inputDS = env.readTextFile("input/sensor-data.log");

        SingleOutputStreamOperator<WaterSensor> sensorDS = inputDS.map(new MyMapFunction());

        //1. 这里不是tuple，scala在此处可以用索引，但java不行。
        //2. 为什么这里key返回的不是string而是tuple？ 因为通过位置索引或字段名称返回key的类型，无法确定，所以会返回Tuple
//        KeyedStream<WaterSensor, Tuple> sensorKSByFieldName = sensorDS.keyBy("id");
        //3. 通过明确的指定key的方式获取到的key就是具体的类型=》实现KeySelector或lambda
        KeyedStream<WaterSensor, String> sensorKSByKeySelector = sensorDS.keyBy(new MyKeySelector());
//        lambda表达式也可
//        KeyedStream<WaterSensor, String> sensorKSByKeySelector = sensorDS.keyBy(WaterSensor::getId);

        env.execute();
    }


    public static class MyKeySelector implements KeySelector<WaterSensor,String >{

        @Override
        public String getKey(WaterSensor value) throws Exception {
            return value.getId();
        }
    }


    /**
     * 实现MapFunction 指定输入的类型，返回的类型
     * 重写Map方法
     */
    public static class MyMapFunction implements MapFunction<String, WaterSensor>{
        @Override
        public WaterSensor map(String value) throws Exception {
            String[] datas = value.split(",");
            return new WaterSensor(datas[0],Long.valueOf(datas[1]),Integer.valueOf(datas[2]));
        }
    }
}
